//index.js
//获取应用实例
var app = getApp()
Page({
  data: {
    shopGoods: [],
    showLoading: true,
    noMoretip: false,
    page: 0,
    searchVal:'',
    errorTip: {
      text: '',
      isShow: false
    }
  },
  onLoad: function () {

  },
  onShow: function () {
    var that = this;
    app.setNavtitle('搜索');
    var data = {};
    var page = that.data.page;
    var searchVal = that.data.searchVal;
    data.map = 'applet_goods_list';
    data.page = page;
    if (searchVal){
      data.keyword = searchVal;
      console.log("搜索关键字");
      console.log(searchVal);
    }
    //发起请求，获取列表列表
    // wx.showToast({
    //   title: '加载中',
    //   icon: 'loading',
    //   mask: true,
    //   duration: 10000
    // });
    
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        if (res.data.ec == 200) {
          var allArr = [];
          var initArr = that.data.shopGoods;
          var curArr = res.data.data;
          var lastPageLength = curArr.length;
          if (page > 0) {
            allArr = initArr.concat(curArr);
          } else {
            allArr = res.data.data;
          }
          that.setData({
            shopGoods: allArr
          })
          if (lastPageLength < 10) {
            that.setData({
              noMoretip: true,
              showLoading: false
            });
          }
          console.log(that.data.shopGoods);
        } else {
          console.log(res.data)
          if (page <= 0) {
            that.setData({
              shopGoods: []
            })
          } else {
            that.setData({
              noMoretip: true,
              showLoading: false
            });
          }
        }
      },
      complete: function () {
        wx.hideToast();
        wx.stopPullDownRefresh();
      }
    });
    app.setCartnum();//更新购物车数量
  },
  onPullDownRefresh: function () {
    this.setData({
      page: 0,
      noMoretip: false,
      showLoading: true
    });
    this.onShow();
    console.log("下拉刷新");
  },
  onReachBottom: function () {
    var that = this;
    console.log("到达页面底部")
    var isMore = that.data.noMoretip;
    var page = that.data.page;
    page++;
    that.setData({
      page: page
    });
    if (isMore) {
      console.log("已完成或正在加载");
    } else {
      that.onShow();
    }
  },
  goodDetail: function (e) {
    var goodId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/subpages1/goodDetail/goodDetail?id=' + goodId
    })
  },
  cancel:function(){
    wx.navigateBack({
      delta: 1
    })
  },
  searchValChange:function(e){
    var searchVal = e.detail.value;
    this.setData({
      searchVal: searchVal
    });
  },
  searchGood:function(){
    var that = this;
    var searchVal = that.data.searchVal;
    if (searchVal.length>0){
      console.log(searchVal);
      that.onPullDownRefresh();
    }else{
      app.errorTip(that, '请输入搜索商品关键字', 2000);
    }
    
  }
})